<?php
function ConfirmPayment( $FinalPaymentAmt )
    {
            /* Gather the information to make the final call to
               finalize the PayPal payment.  The variable nvpstr
               holds the name value pairs
               */


            //Format the other parameters that were stored in the session from the previous calls	
            $token 				= urlencode($_SESSION['TOKEN']);
            $paymentType 		= urlencode($_SESSION['PaymentType']);
            $currencyCodeType 	= urlencode($_SESSION['currencyCodeType']);
            $payerID 			= urlencode($_SESSION['payer_id']);

            $serverName 		= urlencode($_SERVER['SERVER_NAME']);

            $nvpstr  = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=' . $paymentType . '&PAYMENTREQUEST_0_AMT=' . $FinalPaymentAmt;
            $nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName; 

             /* Make the call to PayPal to finalize payment
                If an error occured, show the resulting errors
                */
            $resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);

            /* Display the API response back to the browser.
               If the response from PayPal was a success, display the response parameters'
               If the response was an error, display the errors received using APIError.php.
               */
            $ack = strtoupper($resArray["ACK"]);

            return $resArray;
    }


    function hash_call($methodName,$nvpStr)
    {
        
         /********************************************
	PayPal API Module
	********************************************/
	$PROXY_HOST = '127.0.0.1';
	$PROXY_PORT = '808';

	$SandboxFlag = true;

	$API_UserName="jmadri_1316536185_biz_api1.netosfera.com";
	$API_Password="1316536238";
	$API_Signature="AZjHJfwFTKfkGqcn9gZlj45YBNm7AV6thIp9YRin4jdfjjDGi5c0atvu ";

	// BN Code 	is only applicable for partners
	$sBNCode = "PP-ECWizard";	
	
	if ($SandboxFlag == true) 
	{
		$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
		$PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
	}
	else
	{
		$API_Endpoint = "https://api-3t.paypal.com/nvp";
		$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
	}
        
	$USE_PROXY = false;
	$version="64";

	if (session_id() == "") 
		session_start();
		//declaring of global variables
		//global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
		//global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
		//global $gv_ApiErrorURL;
		//global $sBNCode;

                
                
		//setting the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);

		//turning off the server and peer verification(TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POST, 1);
		
	    //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
	   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
		if($USE_PROXY)
			curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT); 

		//NVPRequest for submitting to server
		$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);

		//setting the nvpreq as POST FIELD to curl
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

		//getting response from server
		$response = curl_exec($ch);

		//convrting NVPResponse to an Associative Array
		$nvpResArray=deformatNVP($response);
		$nvpReqArray=deformatNVP($nvpreq);
		$_SESSION['nvpReqArray']=$nvpReqArray;

		if (curl_errno($ch)) 
		{
			// moving to display page to display curl errors
			  $_SESSION['curl_error_no']=curl_errno($ch) ;
			  $_SESSION['curl_error_msg']=curl_error($ch);

			  //Execute the Error handling module to display errors. 
		} 
		else 
		{
			 //closing the curl
		  	curl_close($ch);
		}

		return $nvpResArray;
	}
        
        function deformatNVP($nvpstr)
	{
		$intial=0;
	 	$nvpArray = array();

		while(strlen($nvpstr))
		{
			//postion of Key
			$keypos= strpos($nvpstr,'=');
			//position of value
			$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

			/*getting the Key and Value values and storing in a Associative Array*/
			$keyval=substr($nvpstr,$intial,$keypos);
			$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
			//decoding the respose
			$nvpArray[urldecode($keyval)] =urldecode( $valval);
			$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
	         }
		 return $nvpArray;
	}





//echo '<pre>';   
//print_r($_GET);   
//echo '</pre>';
//session_start();

	/*==================================================================
	 PayPal Express Checkout Call
	 ===================================================================
	*/



//$_SESSION["payer_id"]=$_GET["token"];
//$_SESSION["TOKEN"]=$_GET["PayerID"];
//$_SESSION["Payment_Amount"];


/*if ( $PaymentOption == "PayPal" )
{*/
	/*
	'------------------------------------
	' The paymentAmount is the total value of 
	' the shopping cart, that was set 
	' earlier in a session variable 
	' by the shopping cart page
	'------------------------------------
	*/
	
	$finalPaymentAmount =  $_SESSION["Payment_Amount"];
	$_SESSION["payer_id"] =  $_GET["PayerID"];
	$invoce =  $_SESSION["invoce"];

		
	/*
	'------------------------------------
	' Calls the DoExpressCheckoutPayment API call
	'
	' The ConfirmPayment function is defined in the file PayPalFunctions.jsp,
	' that is included at the top of this file.
	'-------------------------------------------------
	*/

	$resArray = ConfirmPayment ( $finalPaymentAmount );
	$ack = strtoupper($resArray["ACK"]);
	if( $ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING" )
	{
		
		echo '<pre>';   
			//print_r($resArray);   
		echo '</pre>'; 
		/*
		'********************************************************************************************************************
		'
		' THE PARTNER SHOULD SAVE THE KEY TRANSACTION RELATED INFORMATION LIKE 
		'                    transactionId & orderTime 
		'  IN THEIR OWN  DATABASE
		' AND THE REST OF THE INFORMATION CAN BE USED TO UNDERSTAND THE STATUS OF THE PAYMENT 
		'
		'********************************************************************************************************************
		*/

		$transactionId		= $resArray["PAYMENTINFO_0_TRANSACTIONID"]; // ' Unique transaction ID of the payment. Note:  If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization & Capture APIs. 
		$transactionType 	= $resArray["PAYMENTINFO_0_TRANSACTIONTYPE"]; //' The type of transaction Possible values: l  cart l  express-checkout 
		$paymentType		= $resArray["PAYMENTINFO_0_PAYMENTTYPE"];  //' Indicates whether the payment is instant or delayed. Possible values: l  none l  echeck l  instant 
		$orderTime 			= $resArray["PAYMENTINFO_0_ORDERTIME"];  //' Time/date stamp of payment
		$amt				= $resArray["PAYMENTINFO_0_AMT"];  //' The final amount charged, including any shipping and taxes from your Merchant Profile.
		$currencyCode		= $resArray["PAYMENTINFO_0_CURRENCYCODE"];  //' A three-character currency code for one of the currencies listed in PayPay-Supported Transactional Currencies. Default: USD. 
		$feeAmt				= $resArray["PAYMENTINFO_0_FEEAMT"];  //' PayPal fee amount charged for the transaction
		//$settleAmt			= $resArray["PAYMENTINFO_0_SETTLEAMT"];  //' Amount deposited in your PayPal account after a currency conversion.
		$taxAmt				= $resArray["PAYMENTINFO_0_TAXAMT"];  //' Tax charged on the transaction.
		//$exchangeRate		= $resArray["PAYMENTINFO_0_EXCHANGERATE"];  //' Exchange rate if a currency conversion occurred. Relevant only if your are billing in their non-primary currency. If the customer chooses to pay with a currency other than the non-primary currency, the conversion occurs in the customer’s account.
		
		/*
		' Status of the payment: 
				'Completed: The payment has been completed, and the funds have been added successfully to your account balance.
				'Pending: The payment is pending. See the PendingReason element for more information. 
		*/
		
		$paymentStatus	= $resArray["PAYMENTINFO_0_PAYMENTSTATUS"]; 

		/*
		'The reason the payment is pending:
		'  none: No pending reason 
		'  address: The payment is pending because your customer did not include a confirmed shipping address and your Payment Receiving Preferences is set such that you want to manually accept or deny each of these payments. To change your preference, go to the Preferences section of your Profile. 
		'  echeck: The payment is pending because it was made by an eCheck that has not yet cleared. 
		'  intl: The payment is pending because you hold a non-U.S. account and do not have a withdrawal mechanism. You must manually accept or deny this payment from your Account Overview. 		
		'  multi-currency: You do not have a balance in the currency sent, and you do not have your Payment Receiving Preferences set to automatically convert and accept this payment. You must manually accept or deny this payment. 
		'  verify: The payment is pending because you are not yet verified. You must verify your account before you can accept this payment. 
		'  other: The payment is pending for a reason other than those listed above. For more information, contact PayPal customer service. 
		*/
		
		$pendingReason	= $resArray["PAYMENTINFO_0_PENDINGREASON"];  

		/*
		'The reason for a reversal if TransactionType is reversal:
		'  none: No reason code 
		'  chargeback: A reversal has occurred on this transaction due to a chargeback by your customer. 
		'  guarantee: A reversal has occurred on this transaction due to your customer triggering a money-back guarantee. 
		'  buyer-complaint: A reversal has occurred on this transaction due to a complaint about the transaction from your customer. 
		'  refund: A reversal has occurred on this transaction because you have given the customer a refund. 
		'  other: A reversal has occurred on this transaction due to a reason not listed above. 
		*/
		
		$reasonCode		= $resArray["PAYMENTINFO_0_REASONCODE"];   
	}
	else  
	{
		//Display a user friendly Error on the page using any of the following error information returned by PayPal
		$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
		$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
		$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
		$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
		
		echo "GetExpressCheckoutDetails API call failed. ";
		echo "Detailed Error Message: " . $ErrorLongMsg;
		echo "Short Error Message: " . $ErrorShortMsg;
		echo "Error Code: " . $ErrorCode;
		echo "Error Severity Code: " . $ErrorSeverityCode;
	}
/*}		*/
	
	
	//session_unset();
	//session_destroy();
$invoice = Doctrine_Core::getTable('Invoice')->find($invoce);
//$invoice->setIdTransaction($transactionId);
$invoice->setAuthCode($transactionId);
if ($paymentStatus == "Completed") :
  $invoice->setIsPaid(1);
endif;

$invoice->setPaymentDate(date('Y-m-d'));
$invoice->save();
?>

<table border="0" width="450px" align="center">
    <tr>
        <td colspan="2" align="center"><strong>your payment has been successfully</strong></td>
    </tr>
    <tr>
        <td>
            <strong>transaction Id</strong>
        </td>
        <td> 
            <?=$transactionId;?>
        </td>
    </tr>
    <tr>
        <td>
            <strong>Invoce</strong>
        </td>
        <td> 
            <?=$invoce;?>
        </td>
    </tr>
     <tr>
        <td>
            <strong>status</strong>
        </td>
        <td> 
             <?=$paymentStatus;?>
        </td>
    </tr>
</table>

<table>
  <tbody>
    <tr>
      <th>Id invoice:</th>
      <td><?php echo $invoice->getIdInvoice() ?></td>
    </tr>
    <tr>
      <th>Status:</th>
      <td><?php echo $invoice->getStatus() ?></td>
    </tr>
    <tr>
      <th>Is paid:</th>
      <td><?php echo $invoice->getIsPaid() ?></td>
    </tr>
    <tr>
      <th>Invoice amount:</th>
      <td><?php echo $invoice->getInvoiceAmount() ?></td>
    </tr>
    <tr>
      <th>Shipping amount:</th>
      <td><?php echo $invoice->getShippingAmount() ?></td>
    </tr>
    <tr>
      <th>Tax amount:</th>
      <td><?php echo $invoice->getTaxAmount() ?></td>
    </tr>
    <tr>
      <th>Shipping name:</th>
      <td><?php echo $invoice->getShippingName() ?></td>
    </tr>
    <tr>
      <th>Shipping last name:</th>
      <td><?php echo $invoice->getShippingLastName() ?></td>
    </tr>
    <tr>
      <th>Shipping Company:</th>
      <td><?php echo $invoice->getShippingCompany() ?></td>
    </tr>
    <tr>
      <th>Shipping address:</th>
      <td><?php echo $invoice->getShippingAddress() ?></td>
    </tr>
    <tr>
      <th>Shipping state:</th>
      <td><?php echo $invoice->getShippingState() ?></td>
    </tr>
    <tr>
      <th>Shipping city:</th>
      <td><?php echo $invoice->getShippingCity() ?></td>
    </tr>
    <tr>
      <th>Shipping zip:</th>
      <td><?php echo $invoice->getShippingZip() ?></td>
    </tr>
    <tr>
      <th>Billing address:</th>
      <td><?php echo $invoice->getBillingAddress() ?></td>
    </tr>
    <tr>
      <th>Billing state:</th>
      <td><?php echo $invoice->getBillingState() ?></td>
    </tr>
    <tr>
      <th>Billing city:</th>
      <td><?php echo $invoice->getBillingCity() ?></td>
    </tr>
    <tr>
      <th>Billing zip:</th>
      <td><?php echo $invoice->getBillingZip() ?></td>
    </tr>
    <tr>
      <th>Billing phone:</th>
      <td><?php echo $invoice->getBillingPhone() ?></td>
    </tr>
    <tr>
      <th>Billing fax:</th>
      <td><?php echo $invoice->getBillingFax() ?></td>
    </tr>
    <tr>
      <th>Billing email:</th>
      <td><?php echo $invoice->getBillingEmail() ?></td>
    </tr>
    <tr>
      <th>Billing name:</th>
      <td><?php echo $invoice->getBillingName() ?></td>
    </tr>
    <tr>
      <th>Billing last name:</th>
      <td><?php echo $invoice->getBillingLastName() ?></td>
    </tr>
    <tr>
      <th>Billing company:</th>
      <td><?php echo $invoice->getBillingCompany() ?></td>
    </tr>
    <tr>
      <th>Due date:</th>
      <td><?php echo $invoice->getPaymentDate() ?></td>
    </tr>
  </tbody>
</table>